import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution56 {
    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][2];
        }
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        List<int[]> res = new ArrayList<>();
        res.add(intervals[0]);
        int max = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= max) {
                max = Math.max(intervals[i][1], max);
                res.get(res.size() - 1)[1] = max;
            } else {
                res.add(intervals[i]);
                max = intervals[i][1];
            }
        }
        return res.toArray(new int[res.size()][]);
    }
}
